package com.autoreassociate.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.preference.PreferenceManager;

import com.autoreassociate.MainActivity;
import com.autoreassociate.R;
import com.autoreassociate.SettingActivity;
import com.autoreassociate.analysis.MessageLogManager;
import com.autoreassociate.tool.ConnectionAssociateTool;
import com.autoreassociate.tool.MyUtils;

public class WifiStatusReceiver extends BroadcastReceiver {

	/** WIFI연결 재확인용 */
	public final static String RECHECK_WIFI_DISCONNECTION = "com.wifireconn.receiver.RECHECK_WIFI_DISCONNECTION";
	
	/** WIFI연결 재확인용 */
	public final static Intent RECHECK_WIFI_DISCONNECTION_INTENT = new Intent(RECHECK_WIFI_DISCONNECTION);
	
	/** WIFI연결 재확인용 */
	public final static String RECHECK_WIFI_CONNECTION = "com.wifireconn.receiver.RECHECK_WIFI_CONNECTION";
	
	/** WIFI연결 재확인용 */
	public final static Intent RECHECK_WIFI_CONNECTION_INTENT = new Intent(RECHECK_WIFI_CONNECTION);
	
	
	/** RSSI 메세지 출력용 */
	protected final static String RSSIS_TRENGTH_FORMAT = "@RSSI strength : %s   @SSID : %s";
	
	
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// wifi버튼의 토글 상태를 갱신
		MainActivity.toggleWifiOnOffButton();
				
		//WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		//MainActivity.printVT(wifiManager.getWifiState() + "");

		//SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		
		ConnectionAssociateTool connectionAssociateTool = ConnectionAssociateTool.getInstance();
		
		MessageLogManager messageLogManager = connectionAssociateTool.getMessageLogManager();

		
		if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
			
			boolean isScreenOnStart = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(SettingActivity.BROADCAST_REASSOCIATE_WHEN_SCREEN_ON, false);
			if (isScreenOnStart) {
				messageLogManager.printVT("ACTION_SCREEN_ON");
				connectionAssociateTool.sendPingOrReconnect();
			}
			
			// 슬립상태에서 wifi연결이 변경되었을경우 다른 브로드캐스트로 wifi켜고끄기 기능이 작동하지 않기에
			// 스크린온시에 아래의 체크를 실시.
			
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			if (wifiManager.isWifiEnabled()) {
				// wifi연결해제를 확인
				this.sendWifiOffCheck(context, connectionAssociateTool);
			} else {
				// wifi연결가능을 확인
				this.sendWifiConnRecheck(context, connectionAssociateTool);
			}
		}
		
		
		if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {

			
			// wifi가 켜지거나 꺼졌을 경우.(켜진상태에서의 연결 상태변경과는 다르다!?)
			
			//ConnectivityManager manager =
			//    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
			
			//NetworkInfo wifi2 = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			NetworkInfo wifiInfo = (NetworkInfo)intent.getExtras().get("networkInfo");

			if (wifiInfo.isConnectedOrConnecting()) {
				if (connectionAssociateTool.isAutoStartAlarm()) {
					connectionAssociateTool.startAlarm();
				}
			} else {
				if (connectionAssociateTool.isAutoStartAlarm()) {
					connectionAssociateTool.endAlarm();
				}

				// wifi연결해제를 확인
				this.sendWifiOffCheck(context, connectionAssociateTool);

	            messageLogManager.printVT("WIFI_CONN DISCONNECTED!!!");
			}
		}
		else if (RECHECK_WIFI_DISCONNECTION.equals(intent.getAction())) {
			
			//NetworkInfo wifiInfo = (NetworkInfo)intent.getExtras().get("networkInfo");
			ConnectivityManager manager =
			    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
			
			NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			
			messageLogManager.printVT("RECEIVED RECHECK_WIFI_DISCONNECTION");
			if (wifiInfo.isConnectedOrConnecting()) {
				return;
			}
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			wifiManager.setWifiEnabled(false);
			messageLogManager.printVT("Changing to WIFI OFF!");

			// wifi버튼의 토글 상태를 갱신
			MainActivity.toggleWifiOnOffButton();
		}
		else if (RECHECK_WIFI_CONNECTION.equals(intent.getAction())) {
			
			//wifi연결가능 체크시
			messageLogManager.printVT("RECEIVED RECHECK_WIFI_CONNECTION");
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			if (wifiManager.isWifiEnabled()) {
				messageLogManager.printVT("Wifi already Enabled!!");
				return;
			}
			
			// wifi기동시 자동으로 ap연결이 이루어짐
			wifiManager.setWifiEnabled(true);
			
			// wifi 연결이 안되었을때 다시 끄기 처리
			connectionAssociateTool.shotPendingIntent(RECHECK_WIFI_DISCONNECTION_INTENT, 30000);
            messageLogManager.printVT(new StringBuilder("WIFI ON AND SEND RECHECK_WIFI_DISCONNECTION : ")
            																		 .append(30000)
            																		 .append("ms")
            																		 .toString());
			messageLogManager.printVT("Try Wifi On!!");
			// wifi버튼의 토글 상태를 갱신
			MainActivity.toggleWifiOnOffButton();
			
			// 다음턴의 재연결 체크시점을 설정
			this.sendWifiConnRecheck(context, connectionAssociateTool);
			
		}
		else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
			messageLogManager.printVT("ACTION_WEB_SEARCH");
		}
		else if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
			
			Integer wifiState = (Integer)(intent.getExtras().get("wifi_state"));
			//intent.getExtras().get("previous_wifi_state")
			
			//if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
			if (wifiState.equals(WifiManager.WIFI_STATE_ENABLED)) {
				// 
				connectionAssociateTool.pingIpResetFromDHCP();
				
				if (connectionAssociateTool.isAutoStartAlarm()) {
					connectionAssociateTool.startAlarm();
				}
				messageLogManager.printVT("WIFI START");
				
			//} else if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLING
			} else if (wifiState.equals(WifiManager.WIFI_STATE_DISABLED)) {
				//TODO
				//ConnectionAssociateTool.getInstance().endWifiStatusReciver();
				if (connectionAssociateTool.isAutoStartAlarm()) {
					connectionAssociateTool.endAlarm();
				}
				// Wifi 연결 가능 체크 실행.
				this.sendWifiConnRecheck(context, connectionAssociateTool);
				messageLogManager.printVT("WIFI END");
			}

		}
		
		// wifi버튼의 토글 상태를 갱신
		MainActivity.toggleWifiOnOffButton();
		
		if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())
				|| WifiManager.RSSI_CHANGED_ACTION.equals(intent.getAction())) {
			
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			
			int rssiStrength = wifiManager.getConnectionInfo().getRssi();
			int disconnRssiStrength = connectionAssociateTool.getDisconnectWifiRssiRate();
//			int disconnRssiStrength = 0;
			
//			String disconnRssiStrengthString =
//				sharedPreferences.getString(SettingActivity.BROADCAST_WIFI_DISCONNECT_RSSI_STRENGTH, null);
//			
//			if (disconnRssiStrengthString != null && disconnRssiStrengthString.length() > 0) {
//				disconnRssiStrength = Integer.parseInt(disconnRssiStrengthString);
//			}
			
			if (disconnRssiStrength == 0) {
				//MainActivity.updateRssiStrengthText(null);
				return;
			}
			
			String rssiMessage = String.format(RSSIS_TRENGTH_FORMAT,
                    wifiManager.getConnectionInfo().getRssi(),
                    wifiManager.getConnectionInfo().getSSID());

			MainActivity.updateRssiStrengthText(rssiMessage);
			
			int rssiIconId = 0;
			if (rssiStrength <= -disconnRssiStrength) {
				wifiManager.disconnect();
				
				if (rssiStrength > -60) {
					rssiIconId = R.drawable.stat_sys_wifi_signal_4;
				} else if (rssiStrength > -70) {
					rssiIconId = R.drawable.stat_sys_wifi_signal_3;
				} else if (rssiStrength > -80) {
					rssiIconId = R.drawable.stat_sys_wifi_signal_2;
				} else if (rssiStrength > -90) {
					rssiIconId = R.drawable.stat_sys_wifi_signal_1;
				} else {
					rssiIconId = R.drawable.stat_sys_wifi_signal_0;
				}

				messageLogManager.printVT(rssiMessage + "disconnect!!", rssiIconId);
			} else {
				return;
			}

			if (rssiStrength > -60) {
				rssiIconId = R.drawable.stat_sys_wifi_signal_4;
			} else if (rssiStrength > -70) {
				rssiIconId = R.drawable.stat_sys_wifi_signal_3;
			} else if (rssiStrength > -80) {
				rssiIconId = R.drawable.stat_sys_wifi_signal_2;
			} else if (rssiStrength > -90) {
				rssiIconId = R.drawable.stat_sys_wifi_signal_1;
			} else {
				rssiIconId = R.drawable.stat_sys_wifi_signal_0;
			}
			
			messageLogManager.printVT(rssiMessage, rssiIconId);
		}

	}
	
	/**
	 * wifi 연결 가능 확인
	 * 
	 * @param context
	 * @param connectionAssociateTool
	 */
	public void sendWifiConnRecheck(Context context, ConnectionAssociateTool connectionAssociateTool) {
		
		String autoWifiTurnOnTimeStr =
			PreferenceManager.getDefaultSharedPreferences(context).getString(SettingActivity.BROADCAST_AUTO_WIFI_TURN_ON_CHECK_TIME, null);
	
		int autoWifiTurnOnTimeInt = MyUtils.parseInt(autoWifiTurnOnTimeStr);
	
		if (autoWifiTurnOnTimeInt != 0) {
            
            connectionAssociateTool.shotPendingIntent(RECHECK_WIFI_CONNECTION_INTENT, autoWifiTurnOnTimeInt);
            connectionAssociateTool.getMessageLogManager().printVT(new StringBuilder("SEND RECHECK_WIFI_CONNECTION : ")
            																		.append(autoWifiTurnOnTimeInt)
            																		.append("ms")
            																		.toString());
		}
	}
	
	/**
	 * wifi 연결 해제 확인
	 * 
	 * @param context
	 * @param connectionAssociateTool
	 */
	public void sendWifiOffCheck(Context context, ConnectionAssociateTool connectionAssociateTool) {
		
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		
		if (wifiManager.isWifiEnabled()) {
			String autoWifiTurnOffTimeStr =
				PreferenceManager.getDefaultSharedPreferences(context).getString(SettingActivity.BROADCAST_AUTO_WIFI_TURN_OFF_TIME, null);
		
			int autoWifiTurnOffTimeInt = MyUtils.parseInt(autoWifiTurnOffTimeStr);
			
			if (autoWifiTurnOffTimeInt != 0) {
				// wifi 끄기체크 실행.
				//long firstTime = SystemClock.elapsedRealtime();

	            connectionAssociateTool.shotPendingIntent(RECHECK_WIFI_DISCONNECTION_INTENT, autoWifiTurnOffTimeInt);
	            connectionAssociateTool.getMessageLogManager().printVT(new StringBuilder("SEND RECHECK_WIFI_DISCONNECTION : ")
	            																		 .append(autoWifiTurnOffTimeInt)
	            																		 .append("ms")
	            																		 .toString());
			}
		}
	}

}
